package com.rabbiter.hospital.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbiter.hospital.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    /**
     * 在处理请求前验证token
     * @param request  HTTP请求
     * @param response HTTP响应
     * @param handler  处理器
     * @return 如果token验证成功，则返回true；否则返回false
     * @throws Exception 如果出现异常，则抛出异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 使用Map来存储错误信息
        Map<String, Object> map = new HashMap<>();
        // 获取请求头中的令牌
        String token = request.getHeader("token");
        try {
            // 验证令牌
            JwtUtil.verify(token);
            // 如果令牌验证成功，允许继续处理请求
            return true;
        } catch (SignatureVerificationException e) {
            // 捕获签名验证异常
            e.printStackTrace();
            map.put("msg", "无效签名！");
        } catch (TokenExpiredException e) {
            // 捕获token过期异常
            e.printStackTrace();
            map.put("msg", "token过期！");
        } catch (AlgorithmMismatchException e) {
            // 捕获算法不匹配异常
            e.printStackTrace();
            map.put("msg", "token算法不一致！");
        } catch (Exception e) {
            // 捕获其他所有异常
            e.printStackTrace();
            map.put("msg", "token无效！");
        }
        // 标记验证状态为false
        map.put("state", false);
        // 将错误信息Map转换为JSON字符串
        String json = new ObjectMapper().writeValueAsString(map);
        // 设置响应内容类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 向响应中写入JSON字符串
        response.getWriter().println(json);
        // 不允许继续处理请求
        return false;
    }

}
